#pragma once
#include "wav.h"
#include "memory.h"

bool isFileClosed = false;
uint64_t timeout;

// 定义采样率
const unsigned long SAMPLE_RATE = 44100;//44100
// 定义每个通道的采样数和缓冲区深度
const size_t SAMPLES_PER_CHANNEL = 1024;//1024
const size_t BUFFER_DEPTH = 64;//4

// 参考电压（例如5V）
double referenceVoltage = 4096;

// 创建ADC对象
AdvancedADC adc(AUDIO_INPUT_PIN);

AdvancedDAC dac0(A13);
File recordAudioFile;
File playAudioFile;

int sample_size = 0;
int samples_count = 0;

  // 估算可用内存的函数
int leaveMemory() {
  char *buf;
  int size = 500000; // 可根据需要调整
  while ((buf = (char *)malloc(size -= 1000)) == NULL);
  free(buf);
  return size;
}

void initialWav(){
  pinMode(AUDIO_INPUT_PIN, INPUT);//非必要

  // Initialize ADC with: resolution, sample rate, number of samples per channel, queue depth
  if (!adc.begin(AN_RESOLUTION_16, SAMPLE_RATE, SAMPLES_PER_CHANNEL, BUFFER_DEPTH)) {
      Serial.println("Failed to start ADC!");
      while (1);
  }
}

// void playAudio(){
//   playAudio(RECORD_FILENAME);
// }

void playAudio(const char *fileName){
  Serial.println("Start playing audio ");
  Serial.println("Opening audio file ...");

  if (SD.exists(fileName)){
    Serial.print("已存在 "); Serial.println(fileName); 
  }

  playAudioFile = SD.open(fileName, FILE_READ);
  if (!playAudioFile) {
    Serial.print("打开 ");Serial.print(fileName);Serial.println(" 文件失败！");
    return;
  }

  Serial.println("Reading audio header ...");

  // WAVHeader header;
  // playAudioFile.read(&header, sizeof(header));
  // printWavHeader(header);
  struct wav_header_t {
    char chunkID[4];              //"RIFF" = 0x46464952
    unsigned long chunkSize;      //28 [+ sizeof(wExtraFormatBytes) + wExtraFormatBytes] + sum(sizeof(chunk.id) + sizeof(chunk.size) + chunk.size)
    char format[4];               //"WAVE" = 0x45564157
    char subchunk1ID[4];          //"fmt " = 0x20746D66
    unsigned long subchunk1Size;  //16 [+ sizeof(wExtraFormatBytes) + wExtraFormatBytes]
    unsigned short audioFormat;
    unsigned short numChannels;
    unsigned long sampleRate;
    unsigned long byteRate;
    unsigned short blockAlign;
    unsigned short bitsPerSample;
  };

  wav_header_t header;
  // fread(&header, sizeof(header), 1, file);
  playAudioFile.read(&header, sizeof(header));

  Serial.println("WAV File Header read:");
  char msg[64] = { 0 };
  snprintf(msg, sizeof(msg), "File Type: %s", header.chunkID);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "File Size: %ld", header.chunkSize);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "WAV Marker: %s", header.format);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Format Name: %s", header.subchunk1ID);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Format Length: %ld", header.subchunk1Size);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Format Type: %hd", header.audioFormat);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Number of Channels: %hd", header.numChannels);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Sample Rate: %ld", header.sampleRate);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Sample Rate * Bits/Sample * Channels / 8: %ld", header.byteRate);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Bits per Sample * Channels / 8: %hd", header.blockAlign);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Bits per Sample: %hd", header.bitsPerSample);
  Serial.println(msg);

  /* Find the data section of the WAV file. */
  struct chunk_t {
    char ID[4];
    unsigned long size;
  };

  chunk_t chunk;
  snprintf(msg, sizeof(msg), "id\t"
                             "size");
  Serial.println(msg);
  /* Find data chunk. */
  while (true) {
    // fread(&chunk, sizeof(chunk), 1, file);
    playAudioFile.read(&chunk, sizeof(chunk));
    snprintf(msg, sizeof(msg), "%c%c%c%c\t"
                               "%li",
             chunk.ID[0], chunk.ID[1], chunk.ID[2], chunk.ID[3], chunk.size);
    Serial.println(msg);
    if (*(unsigned int *)&chunk.ID == 0x61746164)
      break;
    /* Skip chunk data bytes. */
    uint32_t pos = playAudioFile.position();
    playAudioFile.seek(pos+chunk.size);
  }


  /* Determine number of samples. */
  // sample_size = header.bitsPerSample / 8;
  // samples_count = header.subchunk2Size * 8 / header.bitsPerSample;
  // char msg[64] = { 0 };
  // snprintf(msg, sizeof(msg), "Sample size = %i", sample_size); Serial.println(msg);
  // snprintf(msg, sizeof(msg), "Samples count = %i", samples_count); Serial.println(msg);

  /* Determine number of samples. */
  sample_size = header.bitsPerSample / 8;
  samples_count = chunk.size * 8 / header.bitsPerSample;
  snprintf(msg, sizeof(msg), "Sample size = %i", sample_size);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Samples count = %i", samples_count);
  Serial.println(msg);

  Serial.println("Reading audio data ...");

  /* Configure the advanced DAC. */
  if (!dac0.begin(AN_RESOLUTION_12, header.sampleRate, 256, 16))
  {
    Serial.println("Failed to start DAC1 !");
    return;
  }

  // short max_amplitude = 0;
  // short min_amplitude = 65535;
  // short mean_amplitude = 0;
  // int num = 0;
  
  while (dac0.available() && playAudioFile.available())
  {
    /* Read data from file. */
    uint16_t sample_data[256] = {0};
    // short sample_data[256] = {0};
    playAudioFile.read(sample_data, sample_size * 256);
  

    /* Get a free buffer for writing. */
    SampleBuffer buf = dac0.dequeue();

    /* Write data to buffer. */
    for (size_t i = 0; i < buf.size(); i++)
    {
      /* Scale down to 12 bit. */
      uint16_t const dac_val = ((static_cast<unsigned int>(sample_data[i])+32768)>>4) & 0x0fff;
      buf[i] = dac_val;
      // max_amplitude = max_amplitude < sample_data[i] ? sample_data[i] : max_amplitude;
      // min_amplitude = min_amplitude > sample_data[i] ? sample_data[i] : min_amplitude;
      // mean_amplitude += sample_data[i];
      // num++;
      // Serial.print("sample_data[i]: ");Serial.println(sample_data[i]);
      // Serial.print("buf[i]: ");Serial.println(buf[i]);
    }

    /* Write the buffer to DAC. */
    dac0.write(buf);
    delay(1);
    if(!dac0.available()){
      delay(4);
    }
    // Serial.print("dac0.available(): ");Serial.println(dac0.available());
    // Serial.print("playAudioFile.available(): ");Serial.println(playAudioFile.available());
  }

  // mean_amplitude = mean_amplitude/num;
  // Serial.print("max_amplitude: ");Serial.println(max_amplitude);
  // Serial.print("min_amplitude: ");Serial.println(min_amplitude);
  // Serial.print("mean_amplitude: ");Serial.println(mean_amplitude);
  // Serial.print("diff_amplitude: ");Serial.println(max_amplitude-min_amplitude);

  dac0.stop();
  playAudioFile.close();
  Serial.println("playing audio finished");

}

bool isStartTest = false;

void beginTestAudio(){
  Serial.println("Start testing audio ");

  // Initialize ADC with: resolution, sample rate, number of samples per channel, queue depth
  if (!adc.begin(AN_RESOLUTION_16, SAMPLE_RATE, SAMPLES_PER_CHANNEL, BUFFER_DEPTH)) {
      Serial.println("Failed to start ADC!");
      while (1);
  }

  long long mean_amplitude = 0;
  short b = 0;
  int num = 0;
  isStartTest = true;

  while(isStartTest) {

    if (adc.available()) {
        // 读取数据缓冲区
        SampleBuffer buf = adc.read();
        // 遍历缓冲区中的每个采样值并进行更改
        for (size_t i = 0; i < buf.size(); ++i) {
          b = adcToVoltage(buf[i], referenceVoltage);
          Serial.print("abs(b): ");Serial.println(abs(b));
          mean_amplitude += abs(b);
          num++;
          Serial.print("mean_amplitude: ");Serial.println(mean_amplitude/num);
        }

        // 释放数据缓冲区
        buf.release();
      }

  }

  adc.stop();
  Serial.println("testing audio finished ");

}

void calculateWavCharacteristic(const char *fileName){

  Serial.println("start calculating WavCharacteristic");

  File wavFile;
  wavFile = SD.open(fileName);
  if (!wavFile) {
    // if the file didn't open, print an error:
    Serial.print("error opening ");Serial.println(fileName);
    return;
  }

  Serial.println("Reading audio header ...");

  struct wav_header_t {
    char chunkID[4];              //"RIFF" = 0x46464952
    unsigned long chunkSize;      //28 [+ sizeof(wExtraFormatBytes) + wExtraFormatBytes] + sum(sizeof(chunk.id) + sizeof(chunk.size) + chunk.size)
    char format[4];               //"WAVE" = 0x45564157
    char subchunk1ID[4];          //"fmt " = 0x20746D66
    unsigned long subchunk1Size;  //16 [+ sizeof(wExtraFormatBytes) + wExtraFormatBytes]
    unsigned short audioFormat;
    unsigned short numChannels;
    unsigned long sampleRate;
    unsigned long byteRate;
    unsigned short blockAlign;
    unsigned short bitsPerSample;
  };

  wav_header_t header;
  // fread(&header, sizeof(header), 1, file);
  wavFile.read(&header, sizeof(header));

  Serial.println("WAV File Header read:");
  char msg[64] = { 0 };
  snprintf(msg, sizeof(msg), "File Type: %s", header.chunkID);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "File Size: %ld", header.chunkSize);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "WAV Marker: %s", header.format);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Format Name: %s", header.subchunk1ID);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Format Length: %ld", header.subchunk1Size);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Format Type: %hd", header.audioFormat);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Number of Channels: %hd", header.numChannels);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Sample Rate: %ld", header.sampleRate);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Sample Rate * Bits/Sample * Channels / 8: %ld", header.byteRate);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Bits per Sample * Channels / 8: %hd", header.blockAlign);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Bits per Sample: %hd", header.bitsPerSample);
  Serial.println(msg);

  /* Find the data section of the WAV file. */
  struct chunk_t {
    char ID[4];
    unsigned long size;
  };

  chunk_t chunk;
  snprintf(msg, sizeof(msg), "id\t"
                             "size");
  Serial.println(msg);
  /* Find data chunk. */
  while (true) {
    // fread(&chunk, sizeof(chunk), 1, file);
    wavFile.read(&chunk, sizeof(chunk));
    snprintf(msg, sizeof(msg), "%c%c%c%c\t"
                               "%li",
             chunk.ID[0], chunk.ID[1], chunk.ID[2], chunk.ID[3], chunk.size);
    Serial.println(msg);
    if (*(unsigned int *)&chunk.ID == 0x61746164)
      break;
    /* Skip chunk data bytes. */
    uint32_t pos = playAudioFile.position();
    wavFile.seek(pos+chunk.size);
  }


  /* Determine number of samples. */
  // sample_size = header.bitsPerSample / 8;
  // samples_count = header.subchunk2Size * 8 / header.bitsPerSample;
  // char msg[64] = { 0 };
  // snprintf(msg, sizeof(msg), "Sample size = %i", sample_size); Serial.println(msg);
  // snprintf(msg, sizeof(msg), "Samples count = %i", samples_count); Serial.println(msg);

  /* Determine number of samples. */
  sample_size = header.bitsPerSample / 8;
  samples_count = chunk.size * 8 / header.bitsPerSample;
  snprintf(msg, sizeof(msg), "Sample size = %i", sample_size);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Samples count = %i", samples_count);
  Serial.println(msg);

  Serial.println("Reading audio data ...");

  short max_amplitude = 0;
  short min_amplitude = 65535;
  long long mean_amplitude = 0;
  int num = 0;

  int16_t sampleData;
  // read from the file until there's nothing else in it:
  while (wavFile.available()) {
    wavFile.read(&sampleData, 2);
    max_amplitude = max_amplitude < sampleData ? sampleData : max_amplitude;
    min_amplitude = min_amplitude > sampleData ? sampleData : min_amplitude;
    mean_amplitude += abs(sampleData);
    // Serial.print("abs(b): ");Serial.println(abs(b));
    // Serial.write(sampleData);
    num++;
    // Serial.print(sampleData);Serial.print(" ");
  }
  // close the file:
  wavFile.close();
  Serial.println(" ");
  Serial.print("max_amplitude: ");Serial.println(max_amplitude);
  Serial.print("min_amplitude: ");Serial.println(min_amplitude);
  Serial.print("mean_amplitude: ");Serial.print(mean_amplitude);Serial.print(" / ");Serial.print(num);Serial.print(" = ");Serial.println(mean_amplitude/num);
  Serial.print("diff_amplitude: ");Serial.println(max_amplitude-min_amplitude);

  Serial.println("calculate WavCharacteristic finished ");
}


// void recordAudio(){
//   recordAudio(RECORD_FILENAME, TIME_RECORD);
// }

void recordAudio(const char *fileName, unsigned long time_record) {

  Serial.println("Start recording audio ");

    // Cleanup if necessary
  if (SD.exists(fileName)){
    Serial.print("已存在 "); Serial.println(fileName); 
    SD.remove(fileName);
    Serial.print("remove file "); Serial.println(fileName); 
  }

  // Initialize ADC with: resolution, sample rate, number of samples per channel, queue depth
  if (!adc.begin(AN_RESOLUTION_16, SAMPLE_RATE, SAMPLES_PER_CHANNEL, BUFFER_DEPTH)) {
      Serial.println("Failed to start ADC!");
      while (1);
  }
  // adc.start(SAMPLE_RATE);

  // 创建WAV文件
  recordAudioFile = SD.open(fileName, FILE_WRITE);
  if (!recordAudioFile) {
    Serial.print("创建 ");Serial.print(fileName);Serial.println(" 文件失败！");
    while (1);
  }
  isFileClosed = false;

  Serial.print("writeWavHeader before Free memory: ");Serial.println(leaveMemory());

  // 写入WAV文件头
  writeWavHeader(recordAudioFile, SAMPLE_RATE, 1, 16);
  // recordAudioFile.close();

  // while (1);
  // set timeout - recoring for 5 seconds
  timeout = millis() + time_record;
  Serial.println("开始录制音频...");

  // short max_amplitude = 0;
  // short min_amplitude = 65535;
  // long long mean_amplitude = 0;
  // short b = 0;
  // int num = 0;

  Serial.print("recordAudio before Free memory: ");Serial.println(leaveMemory());
  uint16_t sample_data[1024] = {0};
  while(!isFileClosed) {
    if (millis() < timeout) {
    // // 从麦克风读取音频数据
    //   int audioData = analogRead(AUDIO_INPUT_PIN);

    //   // 将音频数据转换为16位PCM格式
    //   uint16_t audioSample = map(audioData, 0, 1023, 0, 65535);

    //   // 将音频数据写入文件
    //   recordAudioFile.write((uint8_t *)&audioSample, sizeof(audioSample));
    //   // 等待一段时间
    //   delay(10); // 可以根据需要调整延迟时间
    // 检查是否有ADC测量数据准备好
      if (adc.available()) {
        // 读取数据缓冲区
        SampleBuffer buf = adc.read();
        // Serial.print("buf.size(): ");
        // Serial.println(buf.size());
        // 遍历缓冲区中的每个采样值并进行更改
        for (size_t i = 0; i < buf.size(); ++i) {
          // 例如，将每个采样值除以2
          // Serial.print("buf[");
          // Serial.print(i);
          // Serial.print("]: ");
          // Serial.println(buf[i]);
          // buf[i] /= 2;
          sample_data[i] = (uint16_t)adcToVoltage(buf[i], referenceVoltage);
          // b = adcToVoltage(buf[i], referenceVoltage);
          
          // max_amplitude = max_amplitude < b ? b : max_amplitude;
          // min_amplitude = min_amplitude > b ? b : min_amplitude;
          // mean_amplitude += abs(b);
          // Serial.print("abs(b): ");Serial.println(abs(b));
          // num++;
          // sample_data[i] = (uint16_t)b;
          // Serial.print("sample_data[i] after: ");Serial.println(sample_data[i]);
        }
        
        // 写入数据到WAV文件, buf.size(): number of samples per channel
        recordAudioFile.write(reinterpret_cast<uint8_t *>(sample_data), sizeof(uint16_t) * buf.size());

        // 释放数据缓冲区
        buf.release();
      }
    }else if(!isFileClosed){
      // mean_amplitude = mean_amplitude/num;
      // Serial.print("max_amplitude: ");Serial.println(max_amplitude);
      // Serial.print("min_amplitude: ");Serial.println(min_amplitude);
      // Serial.print("mean_amplitude: ");Serial.print(mean_amplitude);Serial.print(" / ");Serial.print(num);Serial.print(" = ");Serial.println(mean_amplitude/num);
      // Serial.print("diff_amplitude: ");Serial.println(max_amplitude-min_amplitude);
      Serial.print("finishRecording before Free memory: ");Serial.println(leaveMemory());
      finishRecording(fileName);
      isFileClosed = true;
    }
  }
  Serial.print("recordAudio after Free memory: ");Serial.println(leaveMemory());
}

double record_amplification_factor = 1;//录制音频信号放大因子

short adcToVoltage(uint16_t adcValue, double referenceVoltage) {
    int bits = 16; // ADC位数
    // double voltage = (adcValue / (pow(2, bits) - 1.0)) * referenceVoltage; // 计算原始电压值
    // Serial.print("adcValue: ");Serial.println(adcValue);   
    double voltage = (adcValue - (1.25/3.3)*65535)*record_amplification_factor; 
    // Serial.print("voltage: ");Serial.println(voltage);   
    return (short)voltage;
}

void finishRecording(const char *fileName) {
  // // 写入文件头中的Chunk size和Sub-chunk 2 size
  //   recordAudioFile.seek(4);
  //   uint32_t chunkSize = recordAudioFile.size() - 8;
  //   recordAudioFile.write((uint8_t*)&chunkSize, sizeof(chunkSize));

  //   recordAudioFile.seek(40);
  //   uint32_t subChunk2Size = recordAudioFile.size() - 44;
  //   recordAudioFile.write((uint8_t*)&subChunk2Size, sizeof(subChunk2Size));
  // 更新WAV文件头的Chunk size

  // 关闭文件
  recordAudioFile.close();

  delay(100);
  Serial.println("更新wav文件头");

  // 重新打开文件
  recordAudioFile = SD.open(fileName, O_RDWR | O_CREAT);
  if (!recordAudioFile) {
    Serial.print("Failed to open WAV file: ");Serial.println(fileName);
    while (1);
  }
  uint32_t fileSize = recordAudioFile.size() - 8;
  Serial.print("fileSize: ");Serial.println(fileSize);
  // unsigned long fSize = recordAudioFile.size() - 8;
  getFilePosition(recordAudioFile);
  if (!recordAudioFile.seek(4)) {
    Serial.println("Failed to seek to 4");
  }else{
    Serial.print("file seek to ");
    Serial.println(4);
    getFilePosition(recordAudioFile);
  }

  // byte data[4] = {lowByte(fSize),highByte(fSize), (byte)(fSize >> 16), (byte)(fSize >> 24)};
  // recordAudioFile.write(data,4);
  recordAudioFile.write(reinterpret_cast<uint8_t *>(&fileSize), sizeof(fileSize));
  
  // 更新WAV文件头的Sub-chunk 2 size
  // uint32_t dataSize = fileSize - sizeof(WAVHeader);
  uint32_t dataSize = recordAudioFile.size() - sizeof(WAVHeader);
  Serial.print("dataSize: ");Serial.println(dataSize);
  getFilePosition(recordAudioFile);
  if (!recordAudioFile.seek(40)) {
    Serial.println("Failed to seek to 40");
  }else{
    Serial.print("file seek to ");
    Serial.println(40);
    getFilePosition(recordAudioFile);
  }
  // fSize = fSize - 36;
  // data[0] = lowByte(fSize); data[1]=highByte(fSize); data[2]=(byte)(fSize >> 16); data[3]= (byte)(fSize >> 24);
  // recordAudioFile.write((byte*)data,4);
  recordAudioFile.write(reinterpret_cast<uint8_t *>(&dataSize), sizeof(dataSize));

  printFileWavHeader(recordAudioFile);
  Serial.print("file.size: ");
  Serial.println(recordAudioFile.size());
  // 关闭音频文件
  recordAudioFile.close();

  adc.stop();
  Serial.println("录制完成");
  
}

// 写入WAV文件头
void writeWavHeader(File &file, uint32_t sampleRate, uint16_t numChannels, uint16_t bitsPerSample) {
  Serial.println("初始化WavHeader...");

  // char header[] = {
  //   'R', 'I', 'F', 'F', // Chunk ID
  //   0, 0, 0, 0,          // Chunk Size (填充)
  //   'W', 'A', 'V', 'E', // Format
  //   'f', 'm', 't', ' ', // Subchunk1 ID
  //   16, 0, 0, 0,         // Subchunk1 Size
  //   1, 0,                // Audio Format (PCM)
  //   1, 0,                // Number of Channels (Mono)
  //   0x44, 0xAC, 0, 0,    // Sample Rate (44100)
  //   0x88, 0x58, 0, 0,    // Byte Rate (Sample Rate * Num Channels * Bits per Sample / 8)
  //   1, 0,                // Block Align (Num Channels * Bits per Sample / 8)
  //   16, 0,               // Bits per Sample (16-bit PCM)
  //   'd', 'a', 't', 'a', // Subchunk2 ID
  //   0, 0, 0, 0           // Subchunk2 Size (填充)
  // };

  // recordAudioFile.write(header, sizeof(header));
  // 写入WAV文件头
  WAVHeader header;
  strncpy(header.chunkID, "RIFF", 4);
  header.chunkSize = 0;  // 占位，后面再更新
  strncpy(header.format, "WAVE", 4);
  strncpy(header.subchunk1ID, "fmt ", 4);
  header.subchunk1Size = 16;
  header.audioFormat = 1;
  header.numChannels = numChannels;
  header.sampleRate = sampleRate;
  header.bitsPerSample = bitsPerSample;
  header.byteRate = sampleRate * numChannels * bitsPerSample / 8;// 采样率 * 通道数 * 每个采样的比特数/8
  header.blockAlign = numChannels * bitsPerSample / 8;// 通道数 * 每个采样的比特数/8
  strncpy(header.subchunk2ID, "data", 4);
  header.subchunk2Size = 0;  // 占位，后面再更新

  // printWavHeader(header);
  // Serial.print("sizeof(header): ");
  // Serial.println(sizeof(header));
  // uint32_t pos = file.position();
  // Serial.print("current file position is ");
  // Serial.println(pos);

  file.write(reinterpret_cast<uint8_t *>(&header), sizeof(header));

  printFileWavHeader(file);
}

void printFileWavHeader(File &file) {
  Serial.println("Reading recordAudioFile header ...");
  // 获取并打印当前文件指针位置
  uint32_t pos = getFilePosition(file);
  if (!file.seek(0)) {
    Serial.println("Failed to seek to 0");
  }else{
    Serial.print("file seek to ");
    Serial.println(0);
    getFilePosition(file);
  }

  WAVHeader header;
  file.read(&header, sizeof(header));
  printWavHeader(header);
  getFilePosition(file);
  if (!file.seek(pos)) {
    Serial.print("Failed to seek to ");
    Serial.println(pos);
  }else{
    Serial.print("file seek to ");
    Serial.println(pos);
    getFilePosition(file);
  }
  
  
}

//file已经打开
uint32_t getFilePosition(File &file){
  // 获取并打印当前文件指针位置
  uint32_t pos = file.position();
  Serial.print("current file position is ");
  Serial.println(pos);
  return pos;
}

void printWavHeader(WAVHeader header) {

  printWavHeaderFmt(header);
  printWavHeaderData(header);

}

void printWavHeaderFmt(WAVHeader header) {

  Serial.println("WAV Header read:");
  char msg[64] = {0};
  snprintf(msg, sizeof(msg), "File Type: %s", header.chunkID);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "File Size: %ld", header.chunkSize);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "WAV Marker: %s", header.format);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Format Name: %s", header.subchunk1ID);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Format Length: %ld", header.subchunk1Size);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Format Type: %hd", header.audioFormat);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Number of Channels: %hd", header.numChannels);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Sample Rate: %ld", header.sampleRate);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Sample Rate * Bits/Sample * Channels / 8: %ld", header.byteRate);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Bits per Sample * Channels / 8: %hd", header.blockAlign);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Bits per Sample: %hd", header.bitsPerSample);
  Serial.println(msg);
}

void printWavHeaderData(WAVHeader header) {

  char msg[64] = {0};
  snprintf(msg, sizeof(msg), "Data Name: %s", header.subchunk2ID);
  Serial.println(msg);
  snprintf(msg, sizeof(msg), "Data Length: %ld", header.subchunk2Size);
  Serial.println(msg);
}